package utils;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import io.restassured.RestAssured;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;

import static utils.FileUtil.copyFiles;

//写Properties文件
public class WritePropertiesUtil {

    static Logger log = Logger.getLogger(WritePropertiesUtil.class);

    public static void writePropertiesFile(Map<String, String> data) throws IOException {

        String filename = "environment.properties";
        String filename1 = "categories.json";
        // 生成xml文件
        File file = new File(".\\src\\main\\resources\\temp\\" + filename);   //temp目录下

        // 判断是否存在,如果不存在,则创建
        if (!file.exists()) {
            file.createNewFile();
        }
        String filepath = file.getAbsolutePath();

        Properties props = new Properties();
//        InputStream is = WritePropertiesUtil.class.getClassLoader().getResourceAsStream(filepath);
        try {
            InputStream input = new FileInputStream(filepath);
            props.load(input);

            //在保存配置文件之前还需要取得该配置文件的输出流，
            if (data != null) {
                Iterator<Map.Entry<String, String>> iter = data.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    props.setProperty(entry.getKey(), entry.getValue());
                }
            }

            OutputStream out = new FileOutputStream(filepath);
            props.store(out, null);
            input.close();
            out.close();

            //拷贝environment.properties和categories.json文件至allure-results路径下
            File file1 = new File(".\\src\\main\\resources\\temp\\" + filename1);
            File toFile = new File(".\\target\\allure-results\\" + filename);
            File toFile1 = new File(".\\target\\allure-results\\" + filename1);
            copyFiles(file, toFile);
            copyFiles(file1, toFile1);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void copyResources() {
        this.copyFile("src/main/resources/temp/environment.properties", "target/allure-results/environment.properties");
        this.copyFile("src/main/resources/temp/categories.json", "target/allure-results/categories.json");
//        this.copyFile(".\\src\\main\\resources\\temp\\environment.properties",".\\target\\allure-results\\environment.properties");
    }

    /**
     * 复制图片及其他文件
     *
     * @param sourceRelativePath 源文件相对路径
     * @param targetRelativePath 目标文件相对路径
     */
    private void copyFile(String sourceRelativePath, String targetRelativePath) {
        //读取流字节流
        FileInputStream fileInputStream = null;
        //写入流字节流
        OutputStream imageOutputStream = null;
        try {
            File file = new File(sourceRelativePath);
            fileInputStream = new FileInputStream(file);
            log.info(file.getPath());
            //imageInputStream=CopyReportResources.class.getClassLoader().getResourceAsStream(sourceRelativePath);// 与复制的图片关联起来
            imageOutputStream = new FileOutputStream(targetRelativePath);// 与复制到的目的关联起来，这里的图片的名称可以与原来的相同，也可以不一样
            byte[] b = new byte[1024];// 定义字节数组，并指定长度
            int startbyte = -1;
            while ((startbyte = fileInputStream.read(b)) != -1) {// 读取
                imageOutputStream.write(b, 0, startbyte);// 写入，读多少写入多少，所以用 write(b,0,len)
            }
            System.out.println("复制文件成功");
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {

                try {
                    fileInputStream.close();

                } catch (IOException e2) {
                    // TODO: handle exception
                    System.out.println("读取流关闭失败");
                }
            }
            if (imageOutputStream != null) {

                try {
                    imageOutputStream.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                    System.out.println("输出流关闭失败");
                }

            }
        }

    }

    public static void main(String[] args) throws ConfigurationException, IOException {
        Map<String, String> data = new HashMap<>();
        String env = "env.properties";
        data.put("Environment", new GetFileMess().getValue("Environment", env));
        data.put("baseURI", RestAssured.baseURI + ":" + RestAssured.port + RestAssured.basePath);
        data.put("basePath", new GetFileMess().getValue("basePath", env));
        data.put("port", new GetFileMess().getValue("port", env));
        data.put("userName", new GetFileMess().getValue("userName", env));
        data.put("passwd", new GetFileMess().getValue("passwd", env));
        data.put("orgId", new GetFileMess().getValue("orgId", env));
//         data.put();
        writePropertiesFile(data);
        WritePropertiesUtil copyReportResources = new WritePropertiesUtil();

//         copyReportResources.copyResources();

    }
}